#pragma once
#include "Socket.hpp"

using namespace socket_ns;
class Acceptor
{
private:
    SocketPtr _listensockfd;
    InetAddr _addr;

public:
    Acceptor(uint16_t port) : _listensockfd(std::make_unique<Tcp_socket>())
    {
        _listensockfd->BuildListenSocket(port);
    }
    ~Acceptor()
    {
    }
    int Accept()
    {
        while (true)
        {
            errno = 0;
            int statu = 0;
            int fd = _listensockfd->AcceptSocket(&_addr, &statu);
            if (fd > 0)
            {
                LOG(INFO,"NEW Clinet!,addr = %d\n",_addr.GetAddrStr().c_str());
                break;
            }
            else
            {
                //被信号打断系统调用
                if (statu == EINTR)
                {
                    continue;
                }
                else if(statu == EWOULDBLOCK)
                {
                    //读取完毕
                    LOG(INFO,"%s的读事件处理完毕!\n",_addr.GetAddrStr().c_str());
                    break;
                }
                else 
                {
                    //error
                    LOG(ERROR,"accept 异常!\n");
                    break;
                }
            }
        }
        return fd;
    }
    int ListenFd()
    {
        return _listensockfd->SockFd();
    }
};